﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Xml.Linq;

namespace Library
{
    public static class NOWCulture
    {
        public static Dictionary<Culture, Dictionary<string, string>> Dictionary;

        public static void UpdateCurrentCulture(string culture)
        {
            if (Dictionary != null)
            {
                if (Dictionary.Any(item => item.Key.Id == culture))
                {
                    HttpContext.Current.Response.AppendCookie(new HttpCookie("NOW.CurrentUICulture", culture)
                    {
                        Expires = DateTime.Today.AddYears(1)
                    });
                }
            }
        }

        public static string CurrentCulture
        {
            get
            {
                if (HttpContext.Current == null)
                    return Settings.DefaultCulture;

                // set the culture from the route data (url)
                if (HttpContext.Current.Request.RequestContext.RouteData.Values["culture"] != null)
                {
                    var culture = HttpContext.Current.Request.RequestContext.RouteData.Values["culture"].ToString();

                    if (!string.IsNullOrEmpty(culture))
                    {
                        culture = culture.ToLower();

                        if (Dictionary != null)
                        {
                            if (Dictionary.Any(item => item.Key.Id == culture))
                            {
                                HttpContext.Current.Response.AppendCookie(new HttpCookie("NOW.CurrentUICulture", culture)
                                {
                                    Expires = DateTime.Today.AddYears(1)
                                });
                            }

                            return culture;
                        }
                        throw new HttpException(404, "Page not found");
                    }
                }

                // load the culture info from the cookie
                HttpCookie cookie = HttpContext.Current.Request.Cookies["NOW.CurrentUICulture"];
                if (cookie != null)
                {
                    // set the culture by the cookie content
                    return cookie.Value.ToLower();
                }

                // set the culture by the location if not speicified
                return Settings.DefaultCulture;
            }
        }

        public static CultureInfo CurrentCultureInfo
        {
            get { return new CultureInfo(CurrentCulture); }
        }

        public static string GetString(string key)
        {
            return GetString(key, CurrentCulture);
        }

        public static string GetString(string key, string culture)
        {
            if (string.IsNullOrEmpty(key))
                return null;

            foreach (var item in Dictionary)
            {
                if (item.Key.Id == culture)
                {
                    var dic = item.Value;
                    string value;
                    if (dic.TryGetValue(key, out value))
                    {
                        return value;
                    }
                }
            }

            return key;
        }

        public static bool IsCulture(string culture)
        {
            return Dictionary.Any(item => item.Key.Id == culture);
        }

        public static void BuildDictionary()
        {
            var langPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/cultures");
            if (string.IsNullOrEmpty(langPath))
            {
                throw new Exception("The Culture directory is not found");
            }

            Dictionary = new Dictionary<Culture, Dictionary<string, string>>();

            // Get culture directories
            var culturesDirectoryInfo = new DirectoryInfo(langPath);
            var directoreis = culturesDirectoryInfo.GetDirectories();
            foreach (var directoryInfo in directoreis)
            {
                var files = directoryInfo.GetFiles("strings.xml");
                if (files.Length == 1)
                {
                    var xDoc = XDocument.Load(files[0].FullName);
                    Dictionary<string, string> dic = xDoc.Descendants("string").ToDictionary(d => (string)d.Attribute("key"), d => (string)d.Attribute("value"));
                    Debug.Assert(xDoc.Root != null, "xDoc.Root != null");

                    Dictionary.Add(new Culture()
                    {
                        Id = directoryInfo.Name.ToLower(),
                        Name = xDoc.Root.Attribute("name").Value
                    }, dic);
                }
            }
        }

        public sealed class Culture
        {
            public string Id { get; set; }
            public string Name { get; set; }
        }
    }
}
